import paramiko
import time
import _thread
from app.utils import Config

cfg = ""
hostname = ""
port = ""
username = ""
password = ""
timeout = ""

web_socket = None
chan = None

def recvThread():  # 开启一个多线程负责读取返回信息
    global chan
    global web_socket
    global cfg
    global hostname
    global port
    global username
    global password
    global timeout
    cfg = Config.get_config()["ssh_config"]
    hostname = cfg['ip']
    port = cfg['port']
    username = cfg['name']
    password = cfg['pw']
    timeout = 10

    web_socket = None
    chan = None
    while True:
        while chan.recv_ready():
            info = chan.recv(1024).decode('utf-8')
            web_socket.emit("response", {"value": info}, namespace="/Shell")
            time.sleep(0.1)



def Shell(command, ws, id, list):
    global web_socket
    global chan
    global cfg
    global hostname
    global port
    global username
    global password
    global timeout
    cfg = Config.get_config()["ssh_config"]
    hostname = cfg['ip']
    port = cfg['port']
    username = cfg['name']
    password = cfg['pw']
    timeout = 10

    web_socket = ws
    if id not in list:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname, port, username, password)
        chan = ssh.invoke_shell()  # 创建一个交互式的shell窗口
        chan.settimeout(1000)
        _thread.start_new_thread(recvThread, ())
        list[id] = chan
    else:
        chan = list[id]
    time.sleep(0.5)

    """if command == 'quitshell':
        print('Bye Bye!')
        exit(0)"""
    list[id].send(command + '\n')
    return list